package com.bong.panpan.bongcharttools;

import android.app.AlertDialog;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Spinner;

import com.bong.panpan.bongcharttools.adapter.SimpleFragmentPagerAdapter;
import com.bong.panpan.bongcharttools.ble.BleDevice;
import com.bong.panpan.bongcharttools.ble.BleDeviceState;
import com.bong.panpan.bongcharttools.ble.BleInfo;
import com.bong.panpan.bongcharttools.ble.BleLink;
import com.bong.panpan.bongcharttools.ble.HeartBleLink;
import com.bong.panpan.bongcharttools.custom.Constant;
import com.bong.panpan.bongcharttools.custom.MyUtil;
import com.bong.panpan.bongcharttools.custom.SpUtil;
import com.bong.panpan.bongcharttools.fragment.BleServerSettingFragment;
import com.bong.panpan.bongcharttools.fragment.ChartListContents;
import com.bong.panpan.bongcharttools.fragment.ChartListFragment;
import com.bong.panpan.bongcharttools.fragment.DeviceFragment;
import com.bong.panpan.bongcharttools.fragment.ScanFragment;
import com.bong.panpan.bongcharttools.util.Common;
import com.bong.panpan.bongcharttools.util.PermissionRequireActivity;
import com.github.mikephil.charting.charts.LineChart;

import java.io.File;
import java.util.ArrayList;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * Created by panpan on 2017/9/26.
 */

public class HeartRateShowActivity extends PermissionRequireActivity implements
        DrawerLayout.DrawerListener,
        ChartListFragment.OnListFragmentInteractionListener,
        BleServerSettingFragment.OnFragmentInteractionListener,
        ScanFragment.OnScanFragmentListener,
        DeviceFragment.OnDeviceFragmentListener

{
    @InjectView(R.id.chart1)
    LineChart chart1;
    @InjectView(R.id.menu_btn)
    Button menuBtn;
    @InjectView(R.id.begin_btn)
    Button beginBtn;
    @InjectView(R.id.save_btn)
    Button saveBtn;
    @InjectView(R.id.value_check)
    CheckBox valueCheck;
    @InjectView(R.id.circle_check)
    CheckBox circleCheck;
    @InjectView(R.id.mode_spinner)
    Spinner modeSpinner;

    @InjectView(R.id.drawer_layout)
    DrawerLayout drawerLayout;

    @InjectView(R.id.load_btn)
    Button loadBtn;
    @InjectView(R.id.clear_btn)
    Button clearBtn;
    @InjectView(R.id.view_pager)
    ViewPager viewPager;

    private HeartReteShowHelper heartReteShowHelper;
    private ChartListFragment chartListFragment;
    private BleServerSettingFragment bleSetFragment;
    SimpleFragmentPagerAdapter pagerAdapter;
    private Fragment[] fragments;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SpUtil.getInstance().init(getApplicationContext());
        setContentView(R.layout.activity_heart_rate_show);
        ButterKnife.inject(this);
        pagerAdapter = new SimpleFragmentPagerAdapter(getSupportFragmentManager(), this);
        fragments = pagerAdapter.getFragments();
        viewPager.setAdapter(pagerAdapter);

        heartReteShowHelper = new HeartReteShowHelper(
                chart1,
                beginBtn,
                saveBtn,
                clearBtn,
                loadBtn,
                valueCheck,
                circleCheck,
                modeSpinner,
                findViewById(R.id.menu_layout),
                menuBtn,
                this);
        heartReteShowHelper.setUiThreadListener(heartRateRunnable);
        drawerLayout.addDrawerListener(this);
        chartListFragment = ChartListFragment.newInstance(1, 1);
        bleSetFragment = BleServerSettingFragment.newInstance("", "");
        //getSupportFragmentManager().beginTransaction().replace(R.id.drawer_right, chartListFragment, "chart").commit();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.drawer_right, chartListFragment, "chart");
        //transaction.add(R.id.drawer_right, bleSetFragment, "bleSet");
        transaction.commit();
        //drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.RIGHT);
    }

    @OnClick({R.id.menu_btn, R.id.begin_btn, R.id.save_btn, R.id.load_btn, R.id.clear_btn})
    public void onViewClicked(View view) {
        FragmentTransaction transaction;
        switch (view.getId()) {
            case R.id.menu_btn:
                heartReteShowHelper.onMenuClicked();
                break;
            case R.id.begin_btn:
                ArrayList<BleDevice> linkedDevices = ((DeviceFragment) fragments[1]).getLinkedDevices();
                if (linkedDevices.size() > 0) {

                } else {
                    MyUtil.showToast(this, "未连接任何设备");
                }
                heartReteShowHelper.beginClick(beginBtn);
                break;
            case R.id.clear_btn:
                heartReteShowHelper.onClearClicked();
                break;
            case R.id.save_btn:
                heartReteShowHelper.saveClick(saveBtn);
                break;
            case R.id.load_btn:
                //transaction = getSupportFragmentManager().beginTransaction();
                //transaction.hide(bleSetFragment);
                //transaction.show(chartListFragment);
                //transaction.commit();
                drawerLayout.openDrawer(Gravity.RIGHT);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        heartReteShowHelper.onDestory();
        super.onDestroy();
    }

    public ChartListFragment getChartListFragment() {
        return chartListFragment;
    }

    @Override
    public void onDrawerSlide(View drawerView, float slideOffset) {

    }


    @Override
    public void onDrawerOpened(View drawerView) {
        if (drawerView.getId() != R.id.drawer_right) {
            ((ScanFragment) fragments[0]).beginScan();
        } else {
            //drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.RIGHT);
        }
    }


    @Override
    public void onDrawerClosed(View drawerView) {
        if (drawerView.getId() != R.id.drawer_right) {
            ((ScanFragment) fragments[0]).stopScan();
        } else {
            //drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.RIGHT);
        }
    }

    @Override
    public void onDrawerStateChanged(int newState) {

    }

    AlertDialog deleteDialog;

    private void showDeleteDialog(String msg, AlertDialog.OnClickListener listener) {
        if (deleteDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("提示");
            builder.setPositiveButton("确定", listener);
            builder.setNegativeButton("取消", null);
            deleteDialog = builder.create();
        }
        deleteDialog.setMessage(msg);
        deleteDialog.show();
        deleteDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(Color.BLUE);
        deleteDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.RED);
    }

    ChartListContents.ChartListItem deleteChartItem;
    AlertDialog.OnClickListener deleteListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (new File(deleteChartItem.contentPath).delete()) {
                chartListFragment.refreshList();
                Common.showToast(HeartRateShowActivity.this, deleteChartItem.content + "\n已删除");
                deleteChartItem = null;
            } else {
                Common.showToast(HeartRateShowActivity.this, deleteChartItem.content + "\n删除失败");
            }
        }
    };

    @Override
    public void onListFragmentInteraction(ChartListContents.ChartListItem item, int id) {
        if (id % 10 == 0) {
            ArrayList<int[]> chartData = null;
            try {
                heartReteShowHelper.loadChartData(item.contentPath);
                Common.showToast(this, "读取\"" + item.content + "\"成功");
            } catch (Exception e) {
                e.printStackTrace();
                Common.showToast(this, "读取\"" + item.content + "\"失败\r\n" + e.getMessage());
            }
        }
        if (id % 10 == 1) {
            deleteChartItem = item;
            showDeleteDialog("确定删除：\"" + item.content + "\"？\n删除后不可恢复，请谨慎操作！", deleteListener);
        }
        if (id % 10 == 2) {
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("text/plain");
            //intent.setType("image/jpeg");
            intent.putExtra(Intent.EXTRA_TEXT, "心率曲线图");
            intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + item.contentPath.replace(Constant.chartEndName, ".csv")));
            startActivity(Intent.createChooser(intent, "发送至："));
        }
    }

    @Override
    public void onBleSetFragmentInteraction() {
        drawerLayout.closeDrawer(Gravity.RIGHT);
    }

    long time = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (drawerLayout.isDrawerOpen(Gravity.START) || drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
                drawerLayout.closeDrawers();
                return true;
            }
            if (System.currentTimeMillis() - time > 800) {
                Common.showToast(this, "再按一次退出");
                time = System.currentTimeMillis();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onDeviceConnectClick(BleInfo bleInfo, BluetoothDevice device) {
        ((DeviceFragment) fragments[1]).addDevice(bleInfo, device);
    }

    @Override
    public void onDeviceDisConnectClick(BleInfo bleInfo, BluetoothDevice device) {
        ((DeviceFragment) fragments[1]).removeDevice(bleInfo);
    }

    @Override
    public void onDeviceStateChanged(ArrayList<BleDevice> linkedDevices, BleDeviceState state) {
        SimpleFragmentPagerAdapter.count = linkedDevices.size();
        pagerAdapter.notifyDataSetChanged();
        ((ScanFragment) fragments[0]).notifyDataSetChanged();
        if (state == BleDeviceState.DEVICE_STATE_LINKED) {
            for (int i = 0; i < linkedDevices.size(); i++) {
                BleDevice device = linkedDevices.get(i);
                if (device.bleLink != null) {
                    device.bleLink.addBleListener(bleListener);
                }
                if (device.heartBleLink != null) {
                    device.heartBleLink.addBleListener(bleHeartListener);
                }
            }
        }
    }

    Runnable heartRateRunnable = new Runnable() {
        @Override
        public void run() {
            ArrayList<BleDevice> linkedDevices = ((DeviceFragment) fragments[1]).getLinkedDevices();
            for (BleDevice device :
                    linkedDevices) {
                if (device.bleLink != null)
                    device.bleLink.sendData((byte) 0x26, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x52);//bong发送查询心率指令
            }
        }
    };
    private BleLink.BleListener bleListener = new BleLink.BleListener() {
        @Override
        public void OnDeviceStateChanged(BleLink bleLink, BleDeviceState state) {

        }

        @Override
        public void OnDataReceived(BleLink bleLink, byte[] data) {
            if (data[2] == 0x01) {
                heartReteShowHelper.setChartData(bleLink.getName(), MyUtil.byte2Int(data[3]));
            }
        }
    };

    private HeartBleLink.BleListener bleHeartListener = new HeartBleLink.BleListener() {
        @Override
        public void OnDeviceStateChanged(HeartBleLink bleLink, BleDeviceState state) {

        }

        @Override
        public void OnDataReceived(HeartBleLink bleLink, int hr_value, int[] rr_intervals, int rr_intervals_cnt) {
            heartReteShowHelper.setChartData(bleLink.getName(), hr_value);
        }
    };

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            Log.i("HeartRateShowActivity", "竖屏");
        } else {
            Log.i("HeartRateShowActivity", "横屏");
        }
        super.onConfigurationChanged(newConfig);
    }
}
